package com.comtop.springboot.templet.modules.sys.service.impl;

import com.comtop.springboot.templet.common.utils.Constant;
import com.comtop.springboot.templet.modules.sys.mapper.SysUserMapper;
import com.comtop.springboot.templet.modules.sys.mapper.SysUserTokenMapper;
import com.comtop.springboot.templet.modules.sys.entity.SysUserEntity;
import com.comtop.springboot.templet.modules.sys.entity.SysUserTokenEntity;
import com.comtop.springboot.templet.modules.sys.mapper.SysMenuMapper;
import com.comtop.springboot.templet.modules.sys.entity.SysMenuEntity;
import com.comtop.springboot.templet.modules.sys.service.IShiroService;
import com.xiaoleilu.hutool.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ShiroServiceImpl implements IShiroService {
    /**菜单mapper**/
    @Autowired
    private SysMenuMapper sysMenuMapper;
    /**用户mapper**/
    @Autowired
    private SysUserMapper sysUserMapper;
    /**用户token mapper**/
    @Autowired
    private SysUserTokenMapper sysUserTokenMapper;

    @Override
    public Set<String> getUserPermissions(long userId) {
        List<String> permsList;

        //系统管理员，拥有最高权限
        if(userId == Constant.SUPER_ADMIN){
            List<SysMenuEntity> menuList = sysMenuMapper.queryAllMenuList(new HashMap<>());
            permsList = new ArrayList<>(menuList.size());
            for(SysMenuEntity menu : menuList){
                permsList.add(menu.getPerms());
            }
        }else{
            permsList = sysUserMapper.queryUserAllPerms(userId);
        }
        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        for(String perms : permsList){
            if(StrUtil.isBlank(perms)){
                continue;
            }
            permsSet.addAll(Arrays.asList(perms.trim().split(",")));
        }
        return permsSet;
    }

    @Override
    public SysUserTokenEntity queryUserTokenByToken(String token) {
        return sysUserTokenMapper.queryUserTokenByToken(token);
    }

    @Override
    public SysUserEntity queryUserByUserId(Long userId) {
        return sysUserMapper.selectById(userId);
    }
}
